#!/bin/sh

source etc/casperd.conf

# Controllo che esista la directory di lavoro di casper
if [ ! -d $CASPER_WORK_DIR ]; then
	mkdir $CASPER_WORK_DIR
fi

# Controllo che il file esista nel pool
if [ ! -f ${CASPER_POOL_DIR}/$1 ]; then
	echo jobs $2 error file $1 not found
	exit 1
fi

# Creo o svuoto la directory di lavoro del job
if [ ! -d ${CASPER_WORK_DIR}/$2 ]; then
	mkdir ${CASPER_WORK_DIR}/$2
else
	rm -Rf ${CASPER_WORK_DIR}/$2/*
fi

CMD=`echo $1 | awk -v file=${CASPER_POOL_DIR}/$1 -v work_dir=${CASPER_WORK_DIR}/$2/ -F . '{
	if ($NF == "zip") {
		print "unzip " file " -d " work_dir;
	}
	else if ($NF == "gz") {
		c = NF - 1;
		if ($c != "tar")
			exit;
		print "tar zxf " file " -C " work_dir;
	}
	else if ($NF == "bz2") {
		c = NF - 1;
		if ($c != "tar")
			exit;
		print "tar jxf " file " -C " work_dir;
	}
	else if ($NF == "tgz") {
		print "tar zxf " file " -C " work_dir;
	}
	else if ($NF == "tbz" || $NF == "tbz2") {
		print "tar jxf " file " -C " work_dir;
	}
}'`

if [ -z "${CMD}" ]; then
	echo jobs $2 error file format not recognized
	exit 1
fi

# Extracting files
echo jobs $2 status extracting

$CMD > /dev/null
if [ ! $? ]; then
	echo jobs $2 error unable to extract files from archive $1
	exit 1
fi
if [ -f ${CASPER_POOL_DIR}/$1 ]; then
	rm ${CASPER_POOL_DIR}/$1
fi

# Renaming files with spaces in names
find ${CASPER_WORK_DIR}/$2/ | while read fname
do
	if [ ! -f "$fname" ]; then
		continue
	fi
	NewName=`echo $fname | sed -e 'y/ /_/'`
	if [ "$fname" != "$NewName" ]; then
		mv "$fname" "$NewName"
	fi
done

CURR_DIR=`pwd`

EXIT_STATUS=1

export CASPER_BASE_DIR=${CURR_DIR}
export CASPER_CONF_DIR=${CURR_DIR}/etc
export CASPER_RUN_DIR=${CURR_DIR}/${CASPER_RUN_DIR}

for plugin in `ls ${CASPER_PLUGINS_DIR}`
do
	if [ ! -d ${CASPER_PLUGINS_DIR}/$plugin ]; then
		continue
	fi
	if [ ! -x ${CASPER_PLUGINS_DIR}/$plugin/execute.sh ]; then
		continue;
	fi
	cd ${CASPER_PLUGINS_DIR}/$plugin
	./execute.sh ${CASPER_WORK_DIR}/$2
	EXIT_STATUS=$?
	if [ $EXIT_STATUS -eq 0 ]; then
		break
	fi
	cd $CURR_DIR
done

cd $CURR_DIR

exit $EXIT_STATUS
